package com.pavan.gps;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper {
	
	private final Context mContext;
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;
	
	public static final String ROW_ID = "_id";
	public static final String LATITUDE = "lat";
	public static final String LONGITUDE = "lon";
	public static final String TABLE_NAME = "gpslocations";
	public static final String DATABASE_NAME="gpsdetails.db";
	public static final int DATABASE_VERSION=2;
	private static final String CREATE_LIST_TABLE ="create table if not exists " + TABLE_NAME + "(" + ROW_ID + " integer primary key autoincrement," + LATITUDE + " text not null, "+ LONGITUDE + " text not null" + ");";
	public static final int LIST_NAME_COLUMN = 1;
	public static final int TABLE_NAME_COLUMN = 2;
	private static class DatabaseHelper extends SQLiteOpenHelper {
			
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE_LIST_TABLE);
							
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
		}
			
	}
	
	//Constructor
	 public DbHelper (Context context) {
		this.mContext = context;
		
	}
	
	//This method opens data base
	public DbHelper open() throws SQLException {
		mDbHelper = new DatabaseHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}
	
	
	//This method closes database
	public void close() {
		mDbHelper.close();
	}
	
	
	

	public void addItem(String lat,String lon) {
		ContentValues initialValues = new ContentValues();
		
		initialValues.put(LATITUDE, lat);
		initialValues.put(LONGITUDE, lon);
		
		mDb.insert(TABLE_NAME, null, initialValues);
		
	}
	//Gets all lists from the LIST_TABLE_NAME
	public Cursor getAllLists() {
			String[] columns = new String[] {ROW_ID,LATITUDE, LONGITUDE};
			Cursor c = mDb.query(TABLE_NAME, columns, null, null, null, null, null, null);
			if (c!=null) {
				c.moveToFirst();
			}
			return c;
	}
	
	public boolean check(String lat,String lon) {
		
		double latplus=Double.parseDouble(lat)+5;
		double latminus=Double.parseDouble(lat)-5;
		
		double lonplus=Double.parseDouble(lon)+5;
		double lonminus=Double.parseDouble(lon)-5;
		
		
		String q = "select " +LATITUDE+ ","+LONGITUDE+" from gpslocations where "+LATITUDE+"="+latplus+" OR "+latminus+" and "+LONGITUDE+"="+lonplus+" OR "+lonminus+";";
		        Cursor mCursor = mDb.rawQuery(q, null);
				
		        if (mCursor != null) {
		            return true;
		        }
		return false;
	}


}
